package com.baidu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baidu.springcloud.bean.Payment;
import com.baidu.springcloud.common.CommonResult;
import com.baidu.springcloud.myhandler.ConsumerBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-04-04 15:23
 */
@RestController
public class RateLimitController {

    /**
     * 测试按照资源名称来进行限流
     *
     * @return
     */
    @GetMapping("/byResourse")
    @SentinelResource(value = "byResourse", blockHandler = "handle")
    public CommonResult byResourse() {
        return new CommonResult(200, "按照资源名限流测试", new Payment(2020L, "serial001"));
    }

    public CommonResult handle(BlockException exception) {
        return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }


    /**
     * 测试按照url进行限流
     *
     * @return
     */
    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl() {
        return new CommonResult(200, "按照url限流测试", new Payment(2020L, "serial001"));
    }


    /**
     * 测试自定义全局异常处理 限流规则异常时
     *
     * @return
     */
    @GetMapping("/byHandler")
    @SentinelResource(value = "byHandler", blockHandlerClass = ConsumerBlockHandler.class, blockHandler = "handlerException2")
    public CommonResult byHandler() {
        return new CommonResult(200, "按照客户自定义", new Payment(2020L, "serial001"));
    }
}
